package cn.com.oyat.idea.controller.virtual;

import cn.com.oyat.idea.model.DlnaStatus;
import cn.com.oyat.idea.service.AVTransportService;
import cn.com.oyat.idea.util.SoapResponseUtil;
import cn.com.oyat.idea.util.XmlParserUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller
public class DLNAController {

    @Autowired
    private AVTransportService avTransportService;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @GetMapping("/")
    public String index(Model model, HttpServletRequest request) {
        try {
            String localIp = request.getLocalAddr();
            int port = request.getLocalPort();
            DlnaStatus status = avTransportService.getCurrentStatus();

            model.addAttribute("deviceIp", localIp);
            model.addAttribute("devicePort", port);
            model.addAttribute("status", status.getStatus());
            model.addAttribute("videoUrl", status.getCurrentVideoUrl());
            model.addAttribute("videoTitle", status.getCurrentVideoTitle());

        } catch (Exception e) {
            model.addAttribute("deviceIp", "127.0.0.1");
            model.addAttribute("devicePort", "8191");
            model.addAttribute("status", "系统错误");
            model.addAttribute("error", e.getMessage());
        }
        return "index";
    }

    @GetMapping("/getMovie")
    @ResponseBody
    public JSONObject getMovie(Model model, HttpServletRequest request) {

        try {
            String localIp = request.getLocalAddr();
            int port = request.getLocalPort();
            DlnaStatus status = avTransportService.getCurrentStatus();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceIp", localIp);
            jsonObject.put("devicePort", port);
            jsonObject.put("status", status.getStatus());
            jsonObject.put("videoUrl", status.getCurrentVideoUrl());
            jsonObject.put("videoTitle", status.getCurrentVideoTitle());
            return jsonObject;
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceIp", "127.0.0.1");
            jsonObject.put("devicePort", "8191");
            jsonObject.put("status", "系统错误");
            jsonObject.put("error", e.getMessage());
            return jsonObject;
        }
    }

    /**
     * 处理AVTransport请求
     */
    @PostMapping(value = "/upnp/services/avtransport/control",
            produces = MediaType.TEXT_XML_VALUE)
    @ResponseBody
    public String handleAVTransportControl(@RequestBody String soapRequest,
                                           HttpServletRequest request) {

        String clientIp = request.getRemoteAddr();

        // 判断是否是状态查询（无副作用）
        boolean isQueryAction = soapRequest.contains("GetPositionInfo") ||
                soapRequest.contains("GetTransportInfo") ||
                soapRequest.contains("GetMediaInfo");

        if (!isQueryAction) {
            // 只有 SetURI / Play / Stop 等才打醒目日志
            System.out.println("[" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) +
                    "] 🎮 收到控制指令来自: " + clientIp);
        }
        // 查询类请求可选：完全不打日志，或用 DEBUG（这里选择静默）

        try {
            if (soapRequest.contains("SetAVTransportURI")) {
                return handleSetAVTransportURI(soapRequest, clientIp);
            } else if (soapRequest.contains("Play")) {
                return handlePlayCommand(clientIp);
            } else if (soapRequest.contains("Stop")) {
                return handleStopCommand(clientIp);
            } else if (soapRequest.contains("GetPositionInfo")) {
                return handleGetPositionInfo();
            } else if (soapRequest.contains("GetTransportInfo")) {
                return handleGetTransportInfo();
            }

            return SoapResponseUtil.createErrorResponse("401", "Invalid Action");

        } catch (Exception e) {
            System.err.println("处理AVTransport请求失败: " + e.getMessage());
            e.printStackTrace();
            return SoapResponseUtil.createErrorResponse("501", "Action Failed");
        }
    }

    /**
     * 处理SetAVTransportURI请求
     */
    private String handleSetAVTransportURI(String soapRequest, String clientIp) {
        try {
            String videoUrl = xmlParserUtil.extractVideoUrl(soapRequest);
            String videoTitle = xmlParserUtil.extractVideoTitle(soapRequest);

            avTransportService.setAVTransportURI(videoUrl, videoTitle, clientIp);
            return SoapResponseUtil.createSuccessResponse("SetAVTransportURI");
        } catch (Exception e) {
            System.err.println("处理SetAVTransportURI失败: " + e.getMessage());
            return SoapResponseUtil.createErrorResponse("402", "SetURI Failed");
        }
    }

    /**
     * 处理Play请求
     */
    private String handlePlayCommand(String clientIp) {
        try {
            avTransportService.play(clientIp);
            return SoapResponseUtil.createSuccessResponse("Play");
        } catch (Exception e) {
            System.err.println("处理Play命令失败: " + e.getMessage());
            return SoapResponseUtil.createErrorResponse("403", "Play Failed");
        }
    }

    /**
     * 处理Stop请求
     */
    private String handleStopCommand(String clientIp) {
        try {
            avTransportService.stop(clientIp);
            return SoapResponseUtil.createSuccessResponse("Stop");
        } catch (Exception e) {
            System.err.println("处理Stop命令失败: " + e.getMessage());
            return SoapResponseUtil.createErrorResponse("404", "Stop Failed");
        }
    }

    /**
     * 处理GetPositionInfo请求
     */
    private String handleGetPositionInfo() {
        try {
            DlnaStatus status = avTransportService.getCurrentStatus();
            return SoapResponseUtil.createPositionInfoResponse(status.getCurrentVideoUrl());
        } catch (Exception e) {
            System.err.println("处理GetPositionInfo失败: " + e.getMessage());
            return SoapResponseUtil.createErrorResponse("405", "GetPositionInfo Failed");
        }
    }

    /**
     * 处理GetTransportInfo请求
     */
    private String handleGetTransportInfo() {
        try {
            return SoapResponseUtil.createTransportInfoResponse();
        } catch (Exception e) {
            System.err.println("处理GetTransportInfo失败: " + e.getMessage());
            return SoapResponseUtil.createErrorResponse("406", "GetTransportInfo Failed");
        }
    }

    /**
     * 清空状态
     */
    @PostMapping("/clear")
    @ResponseBody
    public String clearStatus() {
        avTransportService.clear();
        return "状态已清空";
    }
}